package priv.bruce.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import priv.bruce.entry.UserInfo;
import priv.bruce.service.UserService;

public class ValidUserInfoServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private UserService userInfo = new UserService();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("application/json;charset=utf-8");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		UserInfo user;
		try {
			user = userInfo.adminLogin(username);
			if (user == null) {
				response.getWriter().append(JSON.toJSONString(new ReturnResult(2, "用户不存在", null)));
			} else if (user.getUser_name().equals(username) && user.getPassword().equals(password)) {
				if (user.getUser_enable() == 0) {
					response.getWriter().append(JSON.toJSONString(new ReturnResult(2, "您的账号已被封禁，请联系管理员解封", null)));
				} else {
					request.getSession().setAttribute("user", user);
					response.getWriter().append(JSON.toJSONString(new ReturnResult(1, "登录成功", user)));
				}
			} else {
				response.getWriter().append(JSON.toJSONString(new ReturnResult(2, "密码错误", null)));
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("application/json;charset=utf-8");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		UserInfo user;
		try {
			user = userInfo.adminLogin(username);
			if (user == null) {
				response.getWriter().append(JSON.toJSONString(new ReturnResult(2, "用户不存在", null)));
			} else if (user.getUser_name().equals(username) && user.getPassword().equals(password)) {

				if (user.getUser_enable() == 0) {
					response.getWriter().append(JSON.toJSONString(new ReturnResult(2, "您的账号已被封禁，请联系管理员解封", null)));
				} else {
					request.getSession().setAttribute("user", user);
					response.getWriter().append(JSON.toJSONString(new ReturnResult(1, "登录成功", user)));
				}
			} else {
				response.getWriter().append(JSON.toJSONString(new ReturnResult(2, "密码错误", null)));
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
